/*
 *
 *  * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 *
 *
 */

package com.iwindplus.mgt.server.dal.repository.power;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.yulichang.repository.JoinCrudRepository;
import com.iwindplus.base.domain.exception.BizException;
import com.iwindplus.mgt.domain.constant.MgtConstant;
import com.iwindplus.mgt.domain.dto.power.PositionDTO;
import com.iwindplus.mgt.domain.enums.MgtCodeEnum;
import com.iwindplus.mgt.domain.vo.power.PositionVO;
import com.iwindplus.mgt.server.dal.mapper.power.PositionMapper;
import com.iwindplus.mgt.server.dal.model.power.PositionDO;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * 职位聚合问层接口类.
 *
 * @author zengdegui
 * @since 2018/9/1
 */
@Repository
public class PositionRepository extends JoinCrudRepository<PositionMapper, PositionDO> {

    /**
     * 批量初始化.
     *
     * @param entities 对象集合
     * @return List<PositionVO>
     */
    @Transactional(rollbackFor = Exception.class)
    public List<PositionVO> saveBatchInit(List<PositionDTO> entities) {
        List<PositionVO> resultList = new ArrayList<>(10);
        AtomicReference<Integer> seq = new AtomicReference<>();
        AtomicBoolean flag = new AtomicBoolean(true);
        List<PositionDTO> saveList = new ArrayList<>(10);
        List<PositionDTO> existList = new ArrayList<>(10);
        entities.forEach(entity -> {
            final PositionDO data = super.getOne(Wrappers.lambdaQuery(PositionDO.class)
                .eq(PositionDO::getName, entity.getName())
                .eq(PositionDO::getDepartmentId, entity.getDepartmentId())
                .eq(PositionDO::getOrgId, entity.getOrgId()));
            if (Objects.isNull(data)) {
                if (flag.get()) {
                    seq.set(this.getNextSeq(entity.getDepartmentId(), entity.getOrgId()));
                    flag.set(false);
                }
                entity.setSeq(seq.getAndSet(seq.get() + 1));
                saveList.add(entity);
            } else {
                final PositionDTO dto = BeanUtil.copyProperties(data, PositionDTO.class);
                existList.add(dto);
            }
        });
        if (CollUtil.isNotEmpty(saveList)) {
            final List<PositionDO> doList = BeanUtil.copyToList(saveList, PositionDO.class);
            super.saveBatch(doList, DEFAULT_BATCH_SIZE);
            final List<PositionVO> voList = BeanUtil.copyToList(doList, PositionVO.class);
            resultList.addAll(voList);
        }
        if (CollUtil.isNotEmpty(existList)) {
            final List<PositionVO> voList = BeanUtil.copyToList(existList, PositionVO.class);
            resultList.addAll(voList);
        }
        return resultList;
    }

    /**
     * 初始化至部门.
     *
     * @param orgId           组织主键
     * @param departmentIdMap 部门主键新旧映射
     * @param entities        集合
     * @return Map<Long, Long>
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<Long, Long> editInitToDepartment(Long orgId, Map<Long, Long> departmentIdMap, List<PositionDTO> entities) {
        Map<Long, Long> idMap = new HashMap<>(16);
        if (CollUtil.isEmpty(entities)) {
            return Collections.emptyMap();
        }
        final List<PositionDO> paramList = BeanUtil.copyToList(entities, PositionDO.class);
        final List<PositionDO> oldList = BeanUtil.copyToList(entities, PositionDO.class);
        this.buildInitList(orgId, departmentIdMap, paramList);
        final List<PositionDTO> dtoList = BeanUtil.copyToList(paramList, PositionDTO.class);
        final List<PositionVO> voList = this.saveBatchInit(dtoList);
        final List<PositionDO> newList = BeanUtil.copyToList(voList, PositionDO.class);
        this.buildIdMap(idMap, oldList, newList);
        return idMap;
    }

    /**
     * 职位名称是否已存在.
     *
     * @param name         职位名称
     * @param departmentId 部门主键
     * @param orgId        组织主键
     */
    public void getNameIsExist(String name, Long departmentId, Long orgId) {
        final LambdaQueryWrapper<PositionDO> queryWrapper = Wrappers.lambdaQuery(PositionDO.class)
            .eq(PositionDO::getName, name)
            .eq(PositionDO::getDepartmentId, departmentId)
            .eq(PositionDO::getOrgId, orgId);
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (result) {
            throw new BizException(MgtCodeEnum.NAME_EXIST);
        }
    }

    /**
     * 职位编码是否已存在.
     *
     * @param code         职位编码
     * @param departmentId 部门主键
     * @param orgId        组织主键
     */
    public void getCodeIsExist(String code, Long departmentId, Long orgId) {
        final LambdaQueryWrapper<PositionDO> queryWrapper = Wrappers.lambdaQuery(PositionDO.class)
            .eq(PositionDO::getCode, code)
            .eq(PositionDO::getDepartmentId, departmentId)
            .eq(PositionDO::getOrgId, orgId);
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (Boolean.TRUE.equals(result)) {
            throw new BizException(MgtCodeEnum.CODE_EXIST);
        }
    }

    /**
     * 查询下一个排序号.
     *
     * @param departmentId 部门主键
     * @param orgId        组织主键
     * @return Integer
     */
    public Integer getNextSeq(Long departmentId, Long orgId) {
        QueryWrapper<PositionDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PositionDO::getDepartmentId, departmentId);
        queryWrapper.lambda().eq(PositionDO::getOrgId, orgId);
        queryWrapper.select("max(seq) as seq");
        Function<Object, Integer> function = val -> Integer.valueOf(val.toString());
        Integer data = super.getObj(queryWrapper, function);
        return Optional.ofNullable(data).map(x -> x + 1).orElse(1);
    }

    private void buildInitList(Long orgId, Map<Long, Long> departmentIdMap, List<PositionDO> entities) {
        entities.forEach(entity -> {
            entity.setId(null);
            entity.setVersion(0);
            entity.setDepartmentId(departmentIdMap.get(entity.getDepartmentId()));
            entity.setOrgId(orgId);
            entity.setRemark(MgtConstant.REMARK_INIT);
        });
        entities.removeIf(m -> Objects.isNull(m.getDepartmentId()) || Objects.isNull(m.getOrgId()));
    }

    private void buildIdMap(Map<Long, Long> idMap, List<PositionDO> oldList, List<PositionDO> newList) {
        oldList.forEach(oldData -> newList.forEach(newData -> {
            if (oldData.getName().equals(newData.getName())) {
                idMap.put(oldData.getId(), newData.getId());
            }
        }));
    }
}
